package flex.cc.vehicle_svr.controller;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.lang.ref.SoftReference;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSONObject;

import flex.cc.basicinformation.entity.ServiceProviderEntity;
import flex.cc.basicinformation.service.ServiceProviderService;
import flex.cc.core.support.BaseController;
import flex.cc.order.manage.dao.OrderServiceProviderDao;
import flex.cc.order.manage.dto.vo.OrderRescuerVo;
import flex.cc.system.entity.DictCodeEntity;
import flex.cc.system.service.DictCodeService;
import flex.cc.vehicle_svr.vo.ResponseVo;

@RestController
@RequestMapping(value = "/vehicleSvr")
public class A extends BaseController {

	@Resource
	private RedisTemplate<String, Object> redisTemplate;
	@Resource
	private DictCodeService dictCodeService;
	@Resource
	private OrderServiceProviderDao orderServiceProviderDao;
	@Resource
	private ServiceProviderService serviceProviderService;
    
	
	@ResponseBody
    @RequestMapping("/redis")
    public JSONObject redis(@RequestBody Map<String,String> map, @RequestHeader Map<String,String> requestHeader) throws Exception {
		
		String serviceItem = map.get("serviceItem");
		String province = map.get("province");
		String city = map.get("city");
		String area = map.get("area");
		String serverId = map.get("serverId");
		List<String> serviceItemList = Arrays.asList(serviceItem.split(","));
    	List<String> provinceList = Arrays.asList(province.split(","));
    	List<String> cityList = Arrays.asList(city.split(","));
    	List<String> areaList = Arrays.asList(area.split(","));
    	Map<String, Object> provider_params = new HashMap<>();
    	provider_params.put("serviceItemList", serviceItemList);
    	provider_params.put("provinceList", provinceList);
    	provider_params.put("cityList", cityList);
    	provider_params.put("areaList", areaList);
    	provider_params.put("status", "1");
    	provider_params.put("servicerId", serverId); //救援商主键
    	boolean realServicer = false;
    	List<ServiceProviderEntity> servicerList = serviceProviderService.findMatchServicer(provider_params);
    	if(servicerList.size()>0){//当前救援商满足
    		realServicer = true;
    	}
    	System.out.println("realServicer=="+realServicer);
		logger.info("vehicleSvr/synStatus 请求头信息："+ requestHeader);
		logger.info("username=="+ requestHeader.get("username"));
		logger.info("Username=="+ requestHeader.get("Username"));
        JSONObject jsonResult = new JSONObject();
        String orderNo = map.get("orderNo");
        String msg = "";
        if(redisTemplate.hasKey(orderNo)){
        	System.out.println("缓存中有此单号");
        	msg = "缓存中有此单号";
        }else{
        	msg = "缓存中没有此单号";
        	redisTemplate.opsForValue().set(orderNo, orderNo, 10, TimeUnit.SECONDS);
        	System.out.println(redisTemplate.hasKey(orderNo));
        }
        
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("typeCode", "carNoVerifyTime");
		DictCodeEntity codeVo = dictCodeService.getOneByParams(params);
		int verifyTime = 0;
		boolean carNoBoolean = false;
		if(codeVo!=null && StringUtils.isNotEmpty(codeVo.getValue())){
			try {
				verifyTime = Integer.valueOf(codeVo.getValue());
        		carNoBoolean = true;
			} catch (Exception e) {
				carNoBoolean = false;
			}
		}
        if(carNoBoolean && verifyTime>0){
        	OrderRescuerVo rescuerVo = orderServiceProviderDao.findRepeatOrderByCarNo_V2("晋MAP379",String.valueOf(verifyTime));
            System.out.println(rescuerVo);
        }
        
        jsonResult.put("resultCode", ResponseVo.SUCCESS_CODE);
		jsonResult.put("message", msg);
		
		Map<String, SoftReference<String>> imgCache = new HashMap<String, SoftReference<String>>();
		SoftReference<String> b = new SoftReference<String>("b");
		imgCache.put("a", b);
		new Thread(new Runnable() {
			@Override
			public void run() {
				System.out.println("------------");
			}
		});
		
		return jsonResult;
    }
	
	
	@ResponseBody
    @RequestMapping("/postXML")
    public JSONObject postXML(@RequestBody Map<String,String> map) throws Exception {
		String jsonStr = JSONUtils.toJSONString(map);
		String soapXml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:cic=\"http://service.interfacemodule.cic.com/\">" +
                "	<soapenv:Header/>" +
                "		<soapenv:Body>" +
                "			<cic:statusWriteBack>" +
                "				<jsonString>"+jsonStr+"</jsonString>" +
                "			</cic:statusWriteBack>" +
                "</soapenv:Body>" +
                "</soapenv:Envelope>";
        String strURL = "https://stcustservice.cic.cn:7103/avs/services/CCService?wsdl";
        logger.info("soapXml-------"+soapXml);
        JSONObject jsonResult = new JSONObject();
        
        URL url = new URL(strURL);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
        conn.setRequestMethod("POST");
        conn.setUseCaches(false);
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setConnectTimeout(10000);
        conn.setReadTimeout(10000);
        
        DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
        dos.write(soapXml.getBytes("utf-8"));//soapXml就是上面生成的xml内容
        dos.flush();
        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
        String line = null;
        StringBuffer strBuf = new StringBuffer();
        while ((line = reader.readLine()) != null) {
            strBuf.append(line);
        }
        dos.close();
        reader.close();
        String rs = strBuf.toString();
        logger.info("postXML结果："+ rs);
        conn.disconnect();
        
        jsonResult.put("resultCode", ResponseVo.SUCCESS_CODE);
		jsonResult.put("message", rs);
		
		return jsonResult;
    }
	
	@ResponseBody
    @RequestMapping("/postXML2")
    public JSONObject postXML2(@RequestBody Map<String,String> map) throws Exception {
		String jsonStr = JSONUtils.toJSONString(map);
		String soapXml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:cic=\"http://service.interfacemodule.cic.com/\">" +
                "	<soapenv:Header/>" +
                "		<soapenv:Body>" +
                "			<cic:statusWriteBack>" +
                "				<jsonString>"+jsonStr+"</jsonString>" +
                "			</cic:statusWriteBack>" +
                "</soapenv:Body>" +
                "</soapenv:Envelope>";
        String strURL = "https://stcustservice.cic.cn:7103/avs/services/CCService?wsdl";
        logger.info("soapXml-------"+soapXml);
        JSONObject jsonResult = new JSONObject();
        
        URL url = new URL(strURL);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
        conn.setRequestMethod("POST");
        conn.setUseCaches(false);
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setConnectTimeout(10000);
        conn.setReadTimeout(10000);
        
        DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
        dos.write(soapXml.getBytes("utf-8"));//soapXml就是上面生成的xml内容
        dos.flush();
        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
        String line = null;
        StringBuffer strBuf = new StringBuffer();
        logger.info("ResponseCode-------"+conn.getResponseCode());
        while ((line = reader.readLine()) != null) {
            strBuf.append(line);
        }
        dos.close();
        reader.close();
        String rs = strBuf.toString();
        
        logger.info("postXML结果："+ rs);
        
        jsonResult.put("resultCode", ResponseVo.SUCCESS_CODE);
		jsonResult.put("message", "信息");
		
		return jsonResult;
    }

}
